package com.yang.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yang.domain.User;
import com.yang.feign.PermissionFeignClient;
import com.yang.mapper.UserMapper;
import com.yang.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionFeignClient permissionFeignClient;

    //用户注册
    @Override
    public boolean registerUser(User user) {
        // 依次验证用户名、邮箱、手机号是否已存在
        if (isUsernameExists(user.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (isEmailExists(user.getEmail())) {
            throw new IllegalArgumentException("邮箱已被使用");
        }
        if (isPhoneExists(user.getPhone())) {
            throw new IllegalArgumentException("手机号已被使用");
        }
        return userMapper.registerUser(user) > 0;
    }

    // 获取用户角色码
    @Override
    public String getUserRoleCode(Long userId) {
        try {
            // 通过RPC调用permission-service查询用户角色码
            return permissionFeignClient.getUserRoleCode(userId);
        } catch (Exception e) {
            System.err.println("查询用户角色码失败: " + e.getMessage());
            throw new RuntimeException("查询用户角色码失败", e);
        }
    }

    // 获取用户列表
    @Override
    public Map<String, Object> getUsersByPage(Long currentUserId, String roleCode, int page, int size) {
        Map<String, Object> result = new HashMap<>();
        List<User> users;
        PageInfo<User> pageInfo;
        switch (roleCode) {
            case "super_admin":
                // 超管可以看到所有用户
                PageHelper.startPage(page, size);
                users = userMapper.selectAllUsers();
                pageInfo = new PageInfo<>(users);
                break;
            case "admin":
                // 管理员可以看到所有普通用户
                PageHelper.startPage(page, size);
                users = userMapper.selectNormalUsers();
                pageInfo = new PageInfo<>(users);
                break;
            case "user":
            default:
                // 普通用户只能看到自己
                User currentUser = userMapper.selectUserByUserId(currentUserId);
                users = currentUser != null ? Arrays.asList(currentUser) : new ArrayList<>();
                // 为普通用户创建简单的分页信息
                pageInfo = new PageInfo<>(users);
                pageInfo.setTotal(users.size());
                pageInfo.setPages(1);
                pageInfo.setPageNum(1);
                pageInfo.setPageSize(size);
                break;
        }
        // 移除密码字段
        users.forEach(user -> user.setPassword(null));
        // 使用PageInfo提供的信息
        result.put("users", users);
        result.put("totalCount", pageInfo.getTotal());
        result.put("currentPage", pageInfo.getPageNum());
        result.put("pageSize", pageInfo.getPageSize());
        result.put("totalPages", pageInfo.getPages());
        result.put("hasNextPage", pageInfo.isHasNextPage());
        result.put("hasPreviousPage", pageInfo.isHasPreviousPage());
        return result;
    }

    // 判断用户名是否存在
    @Override
    public boolean isUsernameExists(String username) {
        return userMapper.selectUserByUsername(username) != null;
    }

    // 判断邮箱是否存在
    @Override
    public boolean isEmailExists(String email) {
        return userMapper.selectUserByEmail(email) != null;
    }

    // 判断手机号是否存在
    @Override
    public boolean isPhoneExists(String phone) {
        return userMapper.selectUserByPhone(phone) != null;
    }

    // 根据用户ID查询用户
    @Override
    public User selectUserByUserId(Long userId) {
        return userMapper.selectUserByUserId(userId);
    }

    // 根据用户名查询用户
    @Override
    public User selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    // 更新用户信息
    @Override
    public boolean updateUser(User user) {
        // 参数验证
        if (user == null || user.getUserId() == null) {
            throw new IllegalArgumentException("用户信息或用户ID不能为空");
        }
        // 检查用户是否存在
        User existingUser = userMapper.selectUserByUserId(user.getUserId());
        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 验证邮箱是否被其他用户使用
        if (user.getEmail() != null && !user.getEmail().equals(existingUser.getEmail())) {
            User userWithEmail = userMapper.selectUserByEmail(user.getEmail());
            if (userWithEmail != null && !userWithEmail.getUserId().equals(user.getUserId())) {
                throw new IllegalArgumentException("邮箱已被其他用户使用");
            }
        }
        // 验证手机号是否被其他用户使用
        if (user.getPhone() != null && !user.getPhone().equals(existingUser.getPhone())) {
            User userWithPhone = userMapper.selectUserByPhone(user.getPhone());
            if (userWithPhone != null && !userWithPhone.getUserId().equals(user.getUserId())) {
                throw new IllegalArgumentException("手机号已被其他用户使用");
            }
        }
        // 验证用户名是否被其他用户使用
        if (user.getUsername() != null && !user.getUsername().equals(existingUser.getUsername())) {
            User userWithUsername = userMapper.selectUserByUsername(user.getUsername());
            if (userWithUsername != null && !userWithUsername.getUserId().equals(user.getUserId())) {
                throw new IllegalArgumentException("用户名已被其他用户使用");
            }
        }
        return userMapper.updateUser(user) > 0;
    }

    // 用户登录
    @Override
    public User loginUser(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        User user = userMapper.loginByUsername(username, password);
        if (user == null) {
            throw new IllegalArgumentException("用户名或密码错误");
        }
        return user;
    }

    // 重置密码
    @Override
    public boolean resetPassword(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("新密码不能为空");
        }
        return userMapper.resetPassword(username, password) > 0;
    }

    // 修改用户信息（权限判定）
    @Override
    public boolean updateUserWithPermission(Long targetUserId, User user, Long currentUserId, String roleCode) {
        // 权限检查
        boolean hasPermission = false;
        switch (roleCode) {
            case "super_admin":
                hasPermission = true;
                break;
            case "admin":
                User targetUser = selectUserByUserId(targetUserId);
                if (targetUser != null) {
                    String targetUserRoleCode = getUserRoleCode(targetUserId);
                    if ("user".equals(targetUserRoleCode) || targetUserId.equals(currentUserId)) {
                        hasPermission = true;
                    }
                }
                break;
            case "user":
            default:
                if (targetUserId.equals(currentUserId)) {
                    hasPermission = true;
                }
                break;
        }
        if (!hasPermission) {
            throw new SecurityException("没有权限修改该用户信息");
        }
        // 创建一个User对象用于更新用户信息
        User updateUser = new User();
        // 设置要更新的用户ID
        updateUser.setUserId(targetUserId);
        updateUser.setUsername(user.getUsername());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());

        // 调用updateUser方法，验证数据唯一性
        return updateUser(updateUser);
    }

    // 查询用户信息（权限判定）
    @Override
    public User getUserByIdWithPermission(Long targetUserId, Long currentUserId, String roleCode) {
        // 权限检查
        boolean hasPermission = false;
        switch (roleCode) {
            case "super_admin":
                // 超管可以查询任何用户
                hasPermission = true;
                break;
            case "admin":
                // 管理员可以查询普通用户和自己
                if (currentUserId.equals(targetUserId)) {
                    // 查询自己
                    hasPermission = true;
                } else {
                    // 查询其他用户，需要检查目标用户是否为普通用户
                    String targetUserRole = getUserRoleCode(targetUserId);
                    hasPermission = "user".equals(targetUserRole);
                }
                break;
            case "user":
                // 普通用户只能查询自己
                hasPermission = currentUserId.equals(targetUserId);
                break;
            default:
                break;
        }
        if (!hasPermission) {
            throw new IllegalArgumentException("权限不足，无法查询该用户信息");
        }
        // 获取用户信息
        User user = selectUserByUserId(targetUserId);
        if (user != null) {
            // 防止密码泄露
            user.setPassword(null);
        }
        return user;
    }

    // 重置密码（权限判定）
    @Override
    public boolean resetPasswordWithPermission(String targetUsername, String newPassword, Long currentUserId, String roleCode) {
        // 参数验证
        if (targetUsername == null || targetUsername.trim().isEmpty()) {
            throw new IllegalArgumentException("目标用户名不能为空");
        }
        if (newPassword == null || newPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("新密码不能为空");
        }
        if (currentUserId == null) {
            throw new IllegalArgumentException("当前用户ID不能为空");
        }
        if (roleCode == null || roleCode.trim().isEmpty()) {
            throw new IllegalArgumentException("用户角色不能为空");
        }
        // 获取目标用户信息
        User targetUser = userMapper.selectUserByUsername(targetUsername);
        if (targetUser == null) {
            throw new IllegalArgumentException("目标用户不存在");
        }
        // 获取目标用户的角色
        String targetUserRoleCode = getUserRoleCode(targetUser.getUserId());
        if (targetUserRoleCode == null) {
            targetUserRoleCode = "user"; // 默认为普通用户
        }
        // 权限检查
        boolean hasPermission = false;
        switch (roleCode) {
            case "super_admin":
                // 超级管理员可以重置任何用户的密码
                hasPermission = true;
                break;
            case "admin":
                // 管理员可以重置普通用户的密码，以及自己的密码
                if ("user".equals(targetUserRoleCode) || targetUser.getUserId().equals(currentUserId)) {
                    hasPermission = true;
                }
                break;
            case "user":
            default:
                // 普通用户只能重置自己的密码
                if (targetUser.getUserId().equals(currentUserId)) {
                    hasPermission = true;
                }
                break;
        }
        if (!hasPermission) {
            throw new SecurityException("没有权限重置该用户的密码");
        }
        return userMapper.resetPassword(targetUsername, newPassword) > 0;
    }

    // 将用户升级为管理员（超管调用）
    @Override
    public boolean upgradeToAdmin(Long targetUserId, Long currentUserId, String roleCode) {
        //权限检查
        if (!roleCode.equals("super_admin")) {
            throw new SecurityException("没有权限升级该用户");
        }
        //参数验证
        if (targetUserId == null || targetUserId <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        if (currentUserId == null || currentUserId <= 0) {
            throw new IllegalArgumentException("当前用户ID无效");
        }
        //检测用户是否存在
        User targetUser = userMapper.selectUserByUserId(targetUserId);
        if (targetUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        //检测用户角色码
        String targetUserRoleCode = getUserRoleCode(targetUserId);
        if ("admin".equals(targetUserRoleCode)) {
            throw new IllegalArgumentException("该用户已经是管理员");
        }
        if ("super_admin".equals(targetUserRoleCode)) {
            throw new IllegalArgumentException("该用户是超级管理员");
        }
        return permissionFeignClient.upgradeToAdmin(targetUserId) > 0;
    }

    // 将管理员降级为普通用户（超管调用）
    @Override
    public boolean downgradeToUser(Long targetUserId, Long currentUserId, String roleCode) {
        //权限检查
        if (!roleCode.equals("super_admin")) {
            throw new SecurityException("没有权限降级该用户");
        }
        //参数验证
        if (targetUserId == null || targetUserId <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        if (currentUserId == null || currentUserId <= 0) {
            throw new IllegalArgumentException("当前用户ID无效");
        }
        //检测用户是否存在
        User targetUser = userMapper.selectUserByUserId(targetUserId);
        if (targetUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        //检测用户角色码
        String targetUserRoleCode = getUserRoleCode(targetUserId);
        if ("user".equals(targetUserRoleCode)) {
            throw new IllegalArgumentException("该用户已经是普通用户");
        }
        if ("super_admin".equals(targetUserRoleCode)) {
            throw new IllegalArgumentException("该用户是超级管理员");
        }
        return permissionFeignClient.downgradeToUser(targetUserId) > 0;
    }
}
